<%@ page language="java" contentType="text/html; charset=UTF-8"
	pageEncoding="UTF-8"%>
<%@ include file="/common/common.jsp"%>
<%-- <%@ include file="/common/commonJs.jsp"%> --%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<%@ include file="/common/seaJs.jsp"%>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<script type="text/javascript" src="${ctx}/js/comm.js"></script>
<script type="text/javascript" src="./enum.js"></script>
<title>表详情编辑</title>
</head>
<body>
	<div id="table">ddd</div>
	<div id="tool"><input type="button" id="create" value="产生"/><input type="button" id="send" value="发送"/></div>
	<div ><textarea id="textarea" style="width:871px;height:350px;"></textarea></div>
</body>

<script>
	//转换文档to html
	function transform(emptyStrutXml,tableColumnXslDoc){
		var resultDocument = null;
		var rowXmlDoc = commLoadXML(emptyStrutXml);
		try {
			if (document.implementation && document.implementation.createDocument) {//webkit
				xsltProcessor = new XSLTProcessor();
				//引入样式表
				xsltProcessor.importStylesheet(tableColumnXslDoc);
				//转换文档
				var resultDoc = xsltProcessor.transformToDocument(rowXmlDoc, document);
				var xmls=new XMLSerializer();
			    resultDocument = xmls.serializeToString(resultDoc);
			}
		} catch (e) {//ie
			//转换文档
			resultDocument = rowXmlDoc.transformNode(tableColumnXslDoc);
		}
		return resultDocument;
	}
	
	/**
	 * xml to string
	 * 
	 */
	function changeXmlDoc2Str(doc) {
		var xml = null;
		try{
			if (document.implementation && document.implementation.createDocument)
				xml = (new XMLSerializer()).serializeToString(doc);
		}catch (e) {
			// TODO: handle exception
			xml = doc.xml;
		}
		return xml;
	}
	
	var ctx = "${ctx}";
	seajs.use([ 'jquery1.8','xslt','jqueryUi' ],function($, xslt_init,jqueryUi_init) {
		xslt_init($);
		var tableColumnXslDoc = commLoad("${ctx}/createTablestruts/tableDetailEditUiTransformor.xsl");
		var tableDefinedXmlDoc = commLoad("${ctx}/createTablestruts/tableDetailEdit.xml");
		var tableXmlStr = changeXmlDoc2Str(tableDefinedXmlDoc);
		var tableXslStr = changeXmlDoc2Str(tableColumnXslDoc);
		$('#table').html(transform(tableXmlStr,tableColumnXslDoc));
		
		$("input[name='removeRow']").live('click',function(){
			$this = $(this);
			$this.parent().parent().remove();
		});
		
		$("input[name='addRow']").live('click',function (){
			$this = $(this);
			var column = '<column name="" id="" tableId="" dataType="" length="" comment="" uuid="" isPk="1"></column>';
			var tableColumnXslDoc = commLoad("${ctx}/createTablestruts/tableDetailEditUiRowTransformor.xsl");
			$this.parent().parent().parent().append(transform(column,tableColumnXslDoc));
		});
		
		$("#send").click(function(){
			
			sendTableXml();
		});
		
		$("#create").click(function(){
			
			createTableDDL();
		});
		
		
		/**
		*/
		function pickData(){
			var tableName = $("[name='tableDetail'] input[name='tableName']:eq(0)");
			var id = $("[name='tableDetail'] input[name='id']:eq(0)");
			
// 			'<column name="" id="" tableId="" dataType="" length="" comment="" uuid="" isPk="0"></column>';
			var columns = '<table name = "'+tableName.val()+'" id = "' + id.val() + '"><columns>';
			var i = 0;
			$("div[name='tableDetail'] tr").each(function(){
				var $this = $(this);
				var length = "";
				if(i >= 2){
					var pattl= /^[1-9]\d*$/;   //正整数的正则
					var lengthVal = $this.find("td [name='length']:eq(0)").val();
					//TODO 判断length 是否正整数 
					if( lengthVal && !pattl.exec(lengthVal) ){
						$this.find("td [name='length']:eq(0)").css('color','red');
						alert("长度应为正整数!");
						return;
					}else if(lengthVal){
						length = "("+$this.find("td [name='length']:eq(0)").val()+")";
					}
					var isPkVal = {'true':'1','false':'0'};
					columns += '<column name="' + $this.find("td [name='name']:eq(0)").val()+'"'+
					   ' isPk = "' +isPkVal[$this.find("td [name='isPk']:eq(0)").prop('checked')] + '"' +
					   ' dataType = "' + $this.find("td [name='dataType']:eq(0)").val() + length + '"' +
					   ' length = "' + $this.find("td [name='length']:eq(0)").val() + '"' +
					   ' default = "' +$this.find("td [name='default']:eq(0)").val() + '"' +
					   ' comment = "' + $this.find("td [name='comment']:eq(0)").val() + '"' +
					   ' uuid = "' + $this.find("td [name='uuid']:eq(0)").val() + '"' +
			  		   ' id = "' + $this.find("td [name='id']:eq(0)").val() + '"' +
			  		   ' tableId = "' + $this.find("td [name='tableId']:eq(0)").val() + '"' +
			  		   '></column>';
				} 
				i++;
			});
			columns += '</columns></table>';
			console.log(columns);
			var x2j = new  xmlToJson(commLoadXML(columns));
			console.log(x2j);
			return columns;
		}
		
		var xmlToJson = function(xml) {
		    var obj = {};
		    if (xml.nodeType == 1) {                
		        if (xml.attributes.length > 0) {
		            obj["@attributes"] = {};
		            for (var j = 0; j < xml.attributes.length; j++) {
		                var attribute = xml.attributes.item(j);
		                obj["@attributes"][attribute.nodeName] = attribute.nodeValue;
		            }
		        }
		    } else if (xml.nodeType == 3) { 
		        obj = xml.nodeValue;
		    }            
		    if (xml.hasChildNodes()) {
		        for (var i = 0; i < xml.childNodes.length; i++) {
		            var item = xml.childNodes.item(i);
		            var nodeName = item.nodeName;
		            if (typeof (obj[nodeName]) == "undefined") {
		                obj[nodeName] = xmlToJson(item);
		            } else {
		                if (typeof (obj[nodeName].push) == "undefined") {
		                    var old = obj[nodeName];
		                    obj[nodeName] = [];
		                    obj[nodeName].push(old);
		                }
		                obj[nodeName].push(xmlToJson(item));
		            }
		        }
		    }
		    return obj;
		};
		
		function sendTableXml(){
			var xml = pickData();
			var url = "${ctx}/dataCreate.action?index=2";
		 	commHttpSend(url, xml, true, "callback", null);
		}
		
		function createTableDDL(){
			var xml =  pickData();
			var tableColumnXslDoc = commLoad("${ctx}/createTablestruts/ddlTransformor.xsl");
			console.log(changeXmlDoc2Str(tableColumnXslDoc)); 
			$("#textarea").val(transform(xml,tableColumnXslDoc));
		}
		
		
	});
	
	function callback(args, datasXmlDoc) {
		alert(datasXmlDoc);
	}
</script>
</html>